﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using DaoShopOnline;

namespace ManageCategoriesProducts
{
    public partial class EditProductWindow : Window
    {
        const int MaxLen = 20;

        public Product ProductToEdit
        {
            get;
            private set;
        }

        public EditProductWindow(Product product)
        {
            InitializeComponent();

            ManageCategories categories = new ManageCategories();
            this.comboBoxCategories.ItemsSource = categories.GetAllCategories();
            this.comboBoxCategories.DisplayMemberPath = "CategoryName";
            this.comboBoxCategories.SelectedValuePath = "CategoryID";

            this.ProductToEdit = product;
            this.DataContext = this.ProductToEdit;
        }

        private void buttonCancel_Click(object sender, RoutedEventArgs e)
        {
            this.DialogResult = false;
        }

        private void buttonEdit_Click(object sender, RoutedEventArgs e)
        {
            if (this.textBoxProductName.Text.Trim() == string.Empty ||
                this.textBoxProductName.Text.Length > MaxLen)
            {
                this.textBoxProductName.Focus();
                ErrorWindow err = new ErrorWindow("Cannot add product!", "Product name lenght must be between 1 and 20.");
                err.ShowDialog();
                return;
            }

            if (this.comboBoxCategories.SelectedItem == null)
            {
                this.comboBoxCategories.Focus();
                ErrorWindow err = new ErrorWindow("Cannot add product!", "Choose product category.");
                err.ShowDialog();
                return;
            }

            double price = 0;
            try
            {

                price = double.Parse(textBoxPrice.Text, System.Globalization.NumberStyles.Currency);
                if (price == 0.0)
                {
                    this.textBoxPrice.Focus();
                    ErrorWindow err = new ErrorWindow("Cannot add product!", "Price must be greater than 0.");
                    err.ShowDialog();
                    return;
                }
            }
            catch (Exception)
            {
                this.textBoxPrice.Focus();
                ErrorWindow err = new ErrorWindow("Cannot add product!", "Enter correct price.");
                err.ShowDialog();
                return;
            }
            this.DialogResult = true;
        }
    }
}
